import type { ConfigProviderThemeVars } from 'wot-design-uni'
import { useUserStore } from '@/store'
import themeJson from '@/theme.json'
import { storeToRefs } from 'pinia'
import { ref } from 'vue'

export type ThemeValueType = 'light' | 'dark'
const theme = ref<ThemeValueType>('light')
const themeVars = ref<ConfigProviderThemeVars>()

export function useTheme(vars?: ConfigProviderThemeVars) {
  const store = useUserStore()
  const { userInfo } = storeToRefs(store)

  /* 替换 Wot 组件的样式 */
  vars && (themeVars.value = vars)

  // 提取 theme.json 中的配置项
  const getThemeValue = (key: string) => {
    return themeJson[theme.value][key] || ''
  }

  const frontColor = computed(() => {
    const value = getThemeValue('navTxtStyle') || 'black'
    if (value === 'black' || value === 'white')
      return value === 'white' ? '#ffffff' : '#000000'
    return value
  })

  const backgroundColor = computed(() => {
    return getThemeValue('navBgColor') || '#ffffff'
  })

  const initNavigationBarColor = () => {
    uni.setNavigationBarColor({
      frontColor: frontColor.value,
      backgroundColor: backgroundColor.value,
      animation: {
        duration: 400,
        timingFunc: 'easeIn',
      },
    })
  }

  const setTheme = () => {
    nextTick(() => {
      if (userInfo.value.followSystem) {
        // #ifdef APP-PLUS
        plus.nativeUI.setUIStyle('auto') // 设置应用主题为跟随系统（android下能够切换，IOS 未测试）
        theme.value = 'light'
        // #endif
        // #ifndef APP-PLUS
        uni.getSystemInfo({
          success: (res: any) => {
            const osThemeInfo = res.hostTheme ? res.hostTheme : res.osTheme
            store.setUserInfo({ theme: osThemeInfo })
            theme.value = osThemeInfo
            initNavigationBarColor()
          },
        })
        // #endif
      }
      else {
        // #ifdef APP-PLUS
        plus.nativeUI.setUIStyle('light') // 设置应用主题为跟随系统（android下能够切换，IOS 未测试）
        // #endif
        initNavigationBarColor()
      }
    })
  }

  watch(theme, () => {
    store.setUserInfo({ theme: theme.value })
    setTheme()
  })

  onShow(() => {
    setTheme()
  })

  return {
    theme,
    themeVars,
    setTheme,
  }
}
